package ren.kane.phoenix.juc;

import java.util.concurrent.Semaphore;

/**
 * @author renrk(1275) on 2019-08-20 2:01 PM
 **/
public class SemaphoreDemo {
    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(10);
        SemaphoreThread t1 = new SemaphoreThread("t1", semaphore);
        SemaphoreThread t2 = new SemaphoreThread("t2", semaphore);
        t1.start();
        t2.start();
        System.out.println(Thread.currentThread().getName() + " trying to acquire");
        try {
            semaphore.acquire(5);
            System.out.println(Thread.currentThread().getName() + " acquire successfully");
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            semaphore.release();
            System.out.println(Thread.currentThread().getName() + " release successfully");
        }
    }
}

class SemaphoreThread extends Thread {
    private Semaphore semaphore;

    public SemaphoreThread(String name, Semaphore semaphore) {
        super(name);
        this.semaphore = semaphore;
    }

    @Override
    public void run() {
        int count = 3;
        System.out.println(Thread.currentThread().getName() + " trying to acquire");
        try {
            semaphore.acquire(count);
            System.out.println(Thread.currentThread().getName() + " acquire successfully");
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            semaphore.release(count);
            System.out.println(Thread.currentThread().getName() + " release successfully");
        }
    }
}